package com.dailyblue.java.cloud.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Component
@Slf4j
public class TokenGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri = exchange.getRequest().getURI().toString();
        log.info("访问路径：{}", exchange.getRequest().getURI());
        if (uri.indexOf("user/login") != -1) {
            return chain.filter(exchange);
        }
        log.info("进入全局token过滤器");
        HttpHeaders headers = exchange.getRequest().getHeaders();
        log.info("内容是:{}", exchange.getRequest().getQueryParams().get("username"));
        log.info("v:{}", exchange.getRequest().getQueryParams());
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        String password = exchange.getRequest().getQueryParams().getFirst("password");
        log.info("接收了用户传递过来的账号：{},密码：{}", username, password);
        log.info("headers:{}", headers);
        String token = headers.get("token") == null ? null : headers.get("token").get(0);
        log.info("token:{}", token);
        String cunde = stringRedisTemplate.opsForValue().get("NAME");
        log.info("cunde:{}", cunde);
        if (cunde == null || !cunde.equals(token)) {
            log.info("用户访问失败！");
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            return exchange.getResponse().setComplete();
        }
        //String uri = "lb://gateway-security/user/login?username=" + username + "&password=" + password;
        //String str = restTemplate.postForEntity(uri, exchange.getRequest(), String.class).getBody();
        //log.info("登陆结果是：{}",str);
        return chain.filter(exchange);
        // 4.拦截
        // 4.1.禁止访问，设置状态码
        //exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2.结束处理
        //return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
